package com.xingdata.jjxc.utils;

import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Consumer implements Runnable {
	public static Consumer consumer;
	final Queue<Task> mQueue;
	public Task mRuningTask;
	private Thread thread;
	private String TAG = "Consumer";

	public Consumer() {
		super();
		this.mQueue = new ConcurrentLinkedQueue<Task>();
	}

	public static Consumer getInstance() {
		if (consumer == null) {
			consumer = new Consumer();
		}
		return consumer;

	}

	public synchronized void add(Task task) {
//		if (mQueue.size()>10) {
//			mQueue.clear();
//		}
		if (!mQueue.contains(task)) {
			mQueue.add(task);
		}
		if (thread == null) {
			thread = new Thread(this);
			thread.start();
		}
	}

	@Override
	public void run() {
		while (true) {
			while (!mQueue.isEmpty()) {
				Log.i(TAG, "Queue  size : "+mQueue.size());
				Task task = mQueue.poll();
				synchronized (this) {
					mRuningTask = task;
				}
				task.runTask();
			}
			synchronized (this) {
				if (mQueue.isEmpty()) {
					thread = null;
					return;
				}
			}
		}
	}

	synchronized public void cancleAll() {
		if (mRuningTask != null) {
			mRuningTask.cacelTask();
		}
		Log.i(TAG, "Remove  Task  size   " + mQueue.size());
		Iterator<Task> iterator = mQueue.iterator();
		while (iterator.hasNext()) {
			Task deleteTask = iterator.next();
			deleteTask.cacelTask();
			mQueue.remove(deleteTask);
		}
	}

	public Queue<Task> getQueue() {
		return mQueue;
	}

}
